export default {
  beforeDestory () {
    // closeWebSocket()
  },
  name: 'App',
  data () {
    return {
      // socket参数
      socket: null,
      timeout: 1500, // 15秒一次心跳
      timeoutObj: null, // 心跳心跳倒计时
      serverTimeoutObj: null, // 心跳倒计时
      timeoutnum: null, // 断开 重连倒计时
      lockReconnect: false, // 防止
      websocket: null
    }
  },
  mounted () {
    this.initWebSocket()
  },
  methods: {
    initWebSocket () {
      console.log('@@@')
      // ws等同于http，wss等同于https
      let wsUrl = 'ws://192.168.137.1:8081/api/websocket' // websocket链接地址
      this.websocket = new WebSocket(wsUrl)
      this.websocket.onopen = this.websocketonopen
      this.websocket.onerror = this.websocketonerror
      this.websocket.onmessage = this.setOnmessageMessage
      this.websocket.onclose = this.websocketclose
    },
    start () {
      console.log('start')
      // 清除延时器
      this.timeoutObj && clearTimeout(this.timeoutObj)
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
      this.timeoutObj = setTimeout(() => {
        if (this.websocket && this.websocket.readyState == 1) {
          var data = { 'code': 1, 'msg': '心跳', 'data': '心跳' }
          this.websocket.send(JSON.stringify(data)) // 给服务端定时发送消息，保持链接
        } else {
          this.reconnect()
        }
        // 定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
        this.serverTimeoutObj = setTimeout(() => {
          this.websocket.close()
        }, this.timeout)
      }, this.timeout)
    },
    reset () { // 重置心跳
      // 清除时间
      clearTimeout(this.timeoutObj)
      clearTimeout(this.serverTimeoutObj)
      // 重启心跳
      this.start()
    },
    // 重新连接
    reconnect () {
      console.log('重连')
      if (this.lockReconnect) return
      this.lockReconnect = true
      // 没连接上会一直重连，设置延迟避免请求过多
      this.timeoutnum && clearTimeout(this.timeoutnum)
      this.timeoutnum = setTimeout(() => {
        this.initWebSocket()
        this.lockReconnect = false
      }, 2000)
    },
    // 监听消息(接收服务端返回的数据)
    async setOnmessageMessage (event) {
      this.reset()
      // 自定义全局监听事件
      window.dispatchEvent(new CustomEvent('onmessageWS', {
        detail: {
          data: event.data
        }
      }))
    },
    websocketonopen () {
      // 开启心跳
      this.start()
      console.log('WebSocket连接成功')
    },
    websocketonerror (e) {
      console.log('WebSocket连接发生错误' + e)
    },
    websocketclose (e) {
      this.websocket.close()
      clearTimeout(this.timeoutObj)
      clearTimeout(this.serverTimeoutObj)
      console.log('WebSocket连接关闭')
      // websocket关闭后重新尝试连接,保持心跳
      setTimeout(() => {
        this.reconnect()
      }, 5000)
    },
    websocketsend (messsage) {
      this.websocket.send(messsage)
    },
    closeWebSocket () { // 关闭websocket
      this.websocket.close()
    }
  }
}
